package pers.supeijin.devtools.converter.wx2vue.converter.template;

import com.intellij.openapi.util.Pair;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlTag;

import java.util.Objects;

/**
 * @author bluefox
 * @date 2021/1/27.
 * 样式属性转换工具
 */

public class StyleAttributeUtils {
	public static final String STYLE_TAG = "style";
	public static final String BIND_STYLE_TAG = ":style";
	public static final String SEMICOLON = ";";

	private StyleAttributeUtils() {
	}

	/**
	 * 转换style 选择器属性
	 * 原始 style="background-color: {{backgroundColor}}; width:{{width}} ; "
	 * 转换后 :style="'background-color': backgroundColor, 'width':width ,"
	 * @param xmlTag
	 */
	public static void converterStyleAttributes(XmlTag xmlTag) {
		if (xmlTag == null) {
			return;
		}
		XmlAttribute attribute = xmlTag.getAttribute(STYLE_TAG);
		if (attribute == null) {
			return;
		}
		String attributeValue = attribute.getValue();
		 boolean isBind = BindUtils.isBindStr(attributeValue);
		 if(isBind){
			 String bindStyleStr = getBindStyleStr(attributeValue);
			 xmlTag.setAttribute(BIND_STYLE_TAG,bindStyleStr);
			 attribute.delete();//删除原来的属性
		 }
	}

    private static String getBindStyleStr(String str){
		String[] strings = str.split(SEMICOLON);
		StringBuilder sb = new StringBuilder();
		sb.append("{");
		for (String attributeStr : strings) {
			String[] propers = attributeStr.split(":");
			sb.append("'")
					.append(propers[0])
					.append("'")
					.append(":")
					.append(getStyleAttributeValue(propers[1]))
					.append(",");
		}
		sb.append("}");
		return sb.toString();
	}
	public static CharSequence getStyleAttributeValue(String attributeValue) {
		Pair<Integer, Integer> bindInfo = BindUtils.getBindInfo(attributeValue);
		if (bindInfo!=null) {
			String bindValue = attributeValue.substring(bindInfo.first+2, bindInfo.second);
			if(attributeValue.length()==bindInfo.second+2){
				//height={{buttonHeight}}
				return bindValue;
			}
			String bindStr = attributeValue.substring(bindInfo.first, bindInfo.second+2);
			String oldText = attributeValue.replace(bindStr, "").trim();
			if(oldText.length()==0){
				return bindValue;
			}
			if(Objects.equals(oldText,"rpx") || Objects.equals(oldText,"px")){
				//border-radius: {{radius}}rpx;
				return bindValue+"/2"+ " + 'px'";
			}
		}
		return attributeValue;
	}
}
